package fun.diaoer.common;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * spring容器工具
 * @author Administrator
 *
 */
@Component
public class SpringContextsUtil implements ApplicationContextAware{

	private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        this.applicationContext = applicationContext;
    }
    
    public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}
    
    /**
	 * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getBean(String name) {
		return (T) applicationContext.getBean(name);
	}

	public static <T> T getBean(Class<? extends T> cls) {
		return applicationContext.getBean(cls);
	}

	public static <T> T getBean(String beanName, Class<? extends T> cls) {
		return applicationContext.getBean(beanName, cls);
	}

}
